package com.jr.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
* 控制 哪些url 不拦截，直接放行
*      哪些utl 拦截，驳回
*
* 1.先判断session里，有没有 user的key
*    ---如果没有，说明没登录：reg.jsp;/reg  ; login.jsp ; /login 是放行的；
*                          除此之后，都拦截
*      如果有，路径都放行！
* 2.
*/

/*@WebFilter("/*")*/
public class InterceptFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    String[] urls={"reg.jsp","reg","login.jsp","login"};
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request=(HttpServletRequest)servletRequest;
        Object user = request.getSession().getAttribute("user");
        if(user==null){//没登录
           if(checkUrl(request)){
               filterChain.doFilter(servletRequest,servletResponse);
           }else{
               ((HttpServletResponse)servletResponse).sendRedirect("/asd/reg.jsp");
           }
        }else{//登录成功
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    public boolean checkUrl(HttpServletRequest request){
        //1.先获得请求地址：
        String requestURI = request.getRequestURI();
        int index=requestURI.lastIndexOf("/")+1;
        String mName = requestURI.substring(index);

        for (String s:urls) {
            if(s.equals(mName)){
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {

    }
}
